package vip.fuxk.blog.data;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import lombok.SneakyThrows;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

public class ListJsonTypeHandler<T> extends BaseTypeHandler<List<T>>  {
    private Class<T> clazz;

    public ListJsonTypeHandler(Class<T> clazz) {
        this.clazz = clazz;
    }

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, List<T> parameter, JdbcType jdbcType) throws SQLException {
        ps.setString(i, JSONUtil.toJsonStr(parameter));
    }

    @Override
    public List<T> getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String data = rs.getString(columnName);
        return StrUtil.isBlank(data) ? null : JSONUtil.parseArray(data).toList(clazz);
    }

    @SneakyThrows
    @Override
    public List<T> getNullableResult(ResultSet rs, int colIndex) {
        String data = rs.getString(colIndex);
        return StrUtil.isBlank(data) ? null : JSONUtil.parseArray(data).toList(clazz);
    }

    @SneakyThrows
    @Override
    public List<T> getNullableResult(CallableStatement cs, int i) {
        String data = cs.getString(i);
        return StrUtil.isBlank(data) ? null : JSONUtil.parseArray(data).toList(clazz);
    }
}

